#include "../Acceptor.h"
#include "../EventLoop.h"
#include "../InetAddress.h"
#include <functional>
using namespace yhaida;

Acceptor::Acceptor(EventLoop *loop, const InetAddress &listenAddr,bool reuseport)
:_mainEventLoop(loop),
_acceptorFd(sockets::createNonblockingOrDie()),//1.
_acceptChannel(loop,_acceptorFd.fd()),
_newConnectionCallback(),
_listenning(false),
_idleFd(::open("/dev/null", O_RDONLY | O_CLOEXEC))
{
    //2.
    assert(_idleFd >= 0);
    _acceptorFd.setReuseAdr(true);
    _acceptorFd.setReusePort(reuseport);//端口重用
    _acceptorFd.bind(listenAddr);

    _acceptChannel.setReadCallBackFuc(std::bind(&Acceptor::handleRead,this));
    // _acceptChannel.enableReading();
}

void Acceptor::listen()
{
    _mainEventLoop->assertInLoopThread();
    _listenning=true;
    //3.
    _acceptorFd.listen();
    _acceptChannel.enableReading();
}

void Acceptor::handleRead()
{
    _mainEventLoop->assertInLoopThread();
    InetAddress addr(0);
    int connfd = _acceptorFd.accept(&addr);
    if(connfd >=0 )
    {
        if(_newConnectionCallback)
        {
            _newConnectionCallback(connfd,addr.getSockAdrrInet());
        }
        else{
            sockets::close(connfd);
        }
    }
}
